# -*- coding: utf-8 -*-
#
# Author:: Jonny
# Date:: 2018/11/29

import getpass
import os
import platform
import re
import socket
import sys
import logging

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S',
                    filename='install.log',
                    filemode='w')

handler = logging.StreamHandler()
logging.root.addHandler(handler)


def update_bat_script(filename, cmd):
    f = open("bat\\raw.bat", "r+", encoding="ANSI")
    content = f.read()
    f.close()
    f = open("bat\\%s" % filename, "w", encoding="ANSI")
    # f.write(content.replace("$COMMANDS", 'cacls "%s" /t /e /g users:f' % PYTHON_PATH))
    f.write(content.replace("$COMMANDS", '%s' % cmd))
    f.close()


def get_admin_privilege_info(_python_path):
    res = os.popen('cacls "%s"' % _python_path)
    res = res.read()
    res_no_space = res.replace(" ", "")
    res_list = res_no_space.split("\n")

    pattern = re.compile(r'.*BUILTIN\\Users.*F')
    has_admin_pri = False
    for item in res_list:
        if pattern.match(item):
            print(item)
            has_admin_pri = True
    return has_admin_pri


def is_exist_path():
    _host_name = socket.gethostname()
    _user_name = getpass.getuser()
    _UserName_win = "%s\\\\%s" % (_host_name, _user_name)
    res = os.popen('''wmic ENVIRONMENT where "name='PATH' and username='%s'"''' % _UserName_win)
    res = res.read()
    if "PATH" in res.upper():
        return True
    else:
        return False


def install_win(_python_path, _project_path):
    _host_name = socket.gethostname()
    _user_name = getpass.getuser()
    _UserName_win = "%s\\\\%s" % (_host_name, _user_name)
    update_bat_script("set_privilege.bat", 'cacls "%s" /t /e /g users:f' % _python_path)
    # update_bat_script("set_path.bat",
    #                   '''wmic ENVIRONMENT where "name='PATH' and username='%s'" set VariableValue="%%PATH%%;%s" ''' % (
    #                       _UserName_win, _project_path))
    # update_bat_script("add_path.bat", 'wmic ENVIRONMENT create name="PATH",username="%s",VariableValue="%s"' % (
    #     _UserName_win, _project_path))

    # 获取Python安装目录权限
    if get_admin_privilege_info(_python_path) == False:
        os.system("bat\\set_privilege.bat")

    '''
    设置环境变量后不会实时更新，使用传统的set path=c业务法更新，可能修改注册表可以实时更新
    所幸echo %path%未显示更新后的变量，但是程序可正常运行，环境变量实际是生效的，且重复添加环境变量并不会产生垃圾数据
    所以，暂时保持现状~
    '''
    # 设置环境变量
    if is_exist_path() == True:
        if _project_path not in os.environ["PATH"]:
            cmd_set_path = '''wmic ENVIRONMENT where "name='PATH' and username='%s'" set VariableValue="%%PATH%%;%s" ''' % (
                _UserName_win, _project_path)
            os.system(cmd_set_path)
    else:
        cmd_add_path = 'wmic ENVIRONMENT create name="PATH",username="%s",VariableValue="%s"' % (
            _UserName_win, _project_path)
        os.system(cmd_add_path)


# 集成到一个文件避免import问题
# 1 获取PYTHON_PATH
pattern = re.compile(r"^.*[0-9]$")
for item in sys.path:
    if "Python" in item and pattern.match(item):
        PYTHON_PATH = item
        break

# 2 获取PROJECT_PATH并写入文件
PROJECT_PATH = sys.path[0]
f = open("compat\\PROJECT_PATH.PY", "w", encoding="utf-8")
f.write('PROJECT_PATH = "%s"' % PROJECT_PATH.strip().replace("\\", "\\\\"))
f.close()

# 3 分类安装
OS_NAME = platform.system()
if OS_NAME == "Windows":
    install_win(PYTHON_PATH, PROJECT_PATH)
elif OS_NAME == "Linux":
    pass
elif OS_NAME == "Mac":
    pass
else:
    pass

# 4 通用操作
# 4.1 安装pipenv并创建virtualenv
os.system("pip install pipenv")
os.system("pipenv install")

# 4.2 获取VIRTUALENV_PATH并记录入文件
res = os.popen("pipenv --venv")
f = open("compat\\" + "VIRTUALENV_PATH.py", "w", encoding="utf-8")
f.write("VIRTUALENV_PATH = '%s'" % res.read().strip().replace("\\", "\\\\"))
